'use client';

import { useState, useEffect } from 'react';
import { STORAGE_KEYS } from '@/lib/constants';

export type Theme = 'light' | 'dark' | 'system';
export type ThemeColor = 'blue' | 'purple' | 'green' | 'red' | 'orange' | 'pink';

// 主题颜色映射
export const themeColorMap: Record<ThemeColor, { 
  color: string, 
  hoverColor: string,
  lightBg: string,
  darkBg: string,
  borderColor: string,
  focusRing: string,
  textLight: string,
  textDark: string,
  gradient: string
}> = {
  blue: { 
    color: '#3b82f6', 
    hoverColor: '#2563eb', 
    lightBg: '#eff6ff', 
    darkBg: '#1e3a8a', 
    borderColor: '#93c5fd', 
    focusRing: 'rgba(59, 130, 246, 0.5)', 
    textLight: '#60a5fa', 
    textDark: '#1d4ed8', 
    gradient: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
  },
  purple: { 
    color: '#8b5cf6', 
    hoverColor: '#7c3aed', 
    lightBg: '#f5f3ff', 
    darkBg: '#5b21b6', 
    borderColor: '#c4b5fd', 
    focusRing: 'rgba(139, 92, 246, 0.5)', 
    textLight: '#a78bfa', 
    textDark: '#6d28d9', 
    gradient: 'linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)'
  },
  green: { 
    color: '#10b981', 
    hoverColor: '#059669', 
    lightBg: '#ecfdf5', 
    darkBg: '#065f46', 
    borderColor: '#6ee7b7', 
    focusRing: 'rgba(16, 185, 129, 0.5)', 
    textLight: '#34d399', 
    textDark: '#047857', 
    gradient: 'linear-gradient(135deg, #10b981 0%, #059669 100%)'
  },
  red: { 
    color: '#ef4444', 
    hoverColor: '#dc2626', 
    lightBg: '#fef2f2', 
    darkBg: '#991b1b', 
    borderColor: '#fca5a5', 
    focusRing: 'rgba(239, 68, 68, 0.5)', 
    textLight: '#f87171', 
    textDark: '#b91c1c', 
    gradient: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)'
  },
  orange: { 
    color: '#f97316', 
    hoverColor: '#ea580c', 
    lightBg: '#fff7ed', 
    darkBg: '#9a3412', 
    borderColor: '#fdba74', 
    focusRing: 'rgba(249, 115, 22, 0.5)', 
    textLight: '#fb923c', 
    textDark: '#c2410c', 
    gradient: 'linear-gradient(135deg, #f97316 0%, #ea580c 100%)'
  },
  pink: { 
    color: '#ec4899', 
    hoverColor: '#db2777', 
    lightBg: '#fdf2f8', 
    darkBg: '#9d174d', 
    borderColor: '#f9a8d4', 
    focusRing: 'rgba(236, 72, 153, 0.5)', 
    textLight: '#f472b6', 
    textDark: '#be185d', 
    gradient: 'linear-gradient(135deg, #ec4899 0%, #db2777 100%)'
  },
};

/**
 * 主题钩子，用于管理应用的主题设置
 */
export function useTheme() {
  const [theme, setThemeState] = useState<Theme>('system');
  const [themeColor, setThemeColorState] = useState<ThemeColor>('blue');
  const [mounted, setMounted] = useState(false);

  // 获取系统偏好主题
  const getSystemTheme = (): 'light' | 'dark' => {
    if (typeof window === 'undefined') return 'light';
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  };

  // 获取当前实际应用的主题
  const resolvedTheme = theme === 'system' ? getSystemTheme() : theme;

  // 从本地存储加载主题设置
  useEffect(() => {
    const storedTheme = localStorage.getItem(STORAGE_KEYS.THEME) as Theme | null;
    const storedThemeColor = localStorage.getItem(STORAGE_KEYS.THEME_COLOR) as ThemeColor | null;
    
    if (storedTheme) {
      setThemeState(storedTheme);
    }
    
    if (storedThemeColor) {
      setThemeColorState(storedThemeColor);
    }
    
    setMounted(true);
  }, []);

  // 监听系统主题变化
  useEffect(() => {
    if (typeof window === 'undefined') return;

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    
    const handleChange = () => {
      if (theme === 'system') {
        document.documentElement.classList.toggle('dark', mediaQuery.matches);
      }
    };

    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, [theme]);

  // 应用主题到文档
  useEffect(() => {
    if (!mounted) return;

    const isDark = resolvedTheme === 'dark';
    document.documentElement.classList.toggle('dark', isDark);
    
    // 更新meta主题颜色
    const metaThemeColor = document.querySelector('meta[name="theme-color"]');
    if (metaThemeColor) {
      metaThemeColor.setAttribute('content', isDark ? '#0a0a0a' : '#ffffff');
    }
  }, [resolvedTheme, mounted]);

  // 应用主题颜色
  useEffect(() => {
    if (!mounted) return;
    
    const colorValues = themeColorMap[themeColor];
    const isDark = resolvedTheme === 'dark';
    
    // 设置基础颜色变量
    document.documentElement.style.setProperty('--primary-color', colorValues.color);
    document.documentElement.style.setProperty('--primary-hover', colorValues.hoverColor);
    
    // 设置扩展的颜色变量，增强全局颜色影响范围
    document.documentElement.style.setProperty('--primary-bg-light', colorValues.lightBg);
    document.documentElement.style.setProperty('--primary-bg-dark', colorValues.darkBg);
    document.documentElement.style.setProperty('--primary-border', colorValues.borderColor);
    document.documentElement.style.setProperty('--primary-focus-ring', colorValues.focusRing);
    document.documentElement.style.setProperty('--primary-text-light', colorValues.textLight);
    document.documentElement.style.setProperty('--primary-text-dark', colorValues.textDark);
    document.documentElement.style.setProperty('--primary-gradient', colorValues.gradient);
    
    // 应用对应主题特定的变量
    document.documentElement.style.setProperty('--accent-color', isDark ? colorValues.textLight : colorValues.textDark);
    document.documentElement.style.setProperty('--selection-bg', colorValues.lightBg);
    document.documentElement.style.setProperty('--selection-text', colorValues.textDark);
    
    // 更新按钮、表单元素等UI组件样式
    document.documentElement.style.setProperty('--button-hover-bg', colorValues.hoverColor);
    document.documentElement.style.setProperty('--input-focus-border', colorValues.color);
    document.documentElement.style.setProperty('--input-focus-shadow', colorValues.focusRing);
    
    // 设置特殊UI元素的风格
    document.documentElement.style.setProperty('--card-highlight', colorValues.borderColor);
    document.documentElement.style.setProperty('--tag-bg', colorValues.lightBg);
    document.documentElement.style.setProperty('--tag-text', colorValues.textDark);
    
    // 设置::selection伪元素的颜色
    const style = document.createElement('style');
    style.innerHTML = `
      ::selection {
        background-color: ${colorValues.lightBg};
        color: ${colorValues.textDark};
      }
    `;
    
    // 移除之前可能存在的自定义样式
    const existingStyle = document.getElementById('theme-selection-style');
    if (existingStyle) {
      existingStyle.remove();
    }
    
    // 添加新样式
    style.id = 'theme-selection-style';
    document.head.appendChild(style);
    
  }, [themeColor, mounted, resolvedTheme]);

  // 设置主题
  const setTheme = (newTheme: Theme) => {
    setThemeState(newTheme);
    localStorage.setItem(STORAGE_KEYS.THEME, newTheme);
  };

  // 设置主题颜色
  const setThemeColor = (newColor: ThemeColor) => {
    setThemeColorState(newColor);
    localStorage.setItem(STORAGE_KEYS.THEME_COLOR, newColor);
  };

  return {
    theme,
    themeColor,
    resolvedTheme,
    setTheme,
    setThemeColor,
    mounted,
  };
} 